<?php

namespace App\Services;

use App\Models\AqConversationDetail;
use App\Models\AqFile;
use App\Models\PreCommonMember;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Slowlyo\OwlAdmin\Services\AdminService;

/**
 * 问答数据
 *
 * @method AqConversationDetail getModel()
 * @method AqConversationDetail|\Illuminate\Database\Query\Builder query()
 */
class AqConversationDetailService extends AdminService
{
	protected string $modelName = AqConversationDetail::class;

	public function sortColumn()
	{
		return $this->getModel()->getCreatedAtColumn();
	}
	public function addRelations($query, string $scene = 'list')
	{
		if($scene == 'list'){
			$query->with(['tool','conversation.user']);
		}
	}
	public function searchable($query)
	{
		parent::searchable($query);
		$query->when($this->request->username, function ($query) {
			$query->whereHas('conversation', function ($query) {
				$uid = PreCommonMember::where('username', $this->request->username)->value('uid');
				$query->where('uid', $uid);
			});
		});
	}

	public function formatRows(array $rows)
	{
		$fileIds = [];
		foreach ($rows as $row) {
			if ($row['request_data']['image_ids']) {
				$fileIds = array_merge($fileIds,$row['request_data']['image_ids']);
			}
			if ($row['request_data']['doc_ids']) {
				$fileIds = array_merge($fileIds,$row['request_data']['doc_ids']);
			}
		}
		$files = $fileIds ? AqFile::whereIn('id',$fileIds)->get()->keyBy('id')->toArray() : [];
		$list = [];
		foreach ($rows as $key => $row){
			$list[$key] = $row->toArray();
			$list[$key]['images'] = $rows[$key]['docs'] = [];
			if ($row['request_data']['image_ids']) {
				foreach ($row['request_data']['image_ids'] as $id)
				{
					if ($file = Arr::get($files,$id))
					{
						$list[$key]['images'][] = [
							'image' => $file['filepath']
						];
					}
				}
			}
			if ($row['request_data']['doc_ids']) {
				foreach ($row['request_data']['doc_ids'] as $id)
				{
					if ($file = Arr::get($files,$id))
					{
						$list[$key]['docs'] = $file;
					}
				}
			}
		}
		return $list;
	}

	public function getCount()
	{
		if($created_at = Arr::get($this->request->all(),'created_at'))
		{
			$created_at = explode(',',$created_at);
			$created_at = [
				Carbon::parse($created_at[0])->startOfDay()->toDateTimeString(),
				Carbon::parse($created_at[1])->endOfDay()->toDateTimeString(),
			];
		}else{
			$created_at = [
				Carbon::now()->subMonth()->toDateTimeString(),
				Carbon::now()->endOfDay()->toDateTimeString(),
			];
		}
		//根据created_at获取每一天的日期
		$startDate = Carbon::parse($created_at[0]);
		$endDate = Carbon::parse($created_at[1]);

		$dates = [];
		$currentDate = $startDate->copy();

		while ($currentDate <= $endDate) {
			$dates[] = $currentDate->format('Y-m-d');
			$currentDate->addDay();
		}
		//读取所有数据
		$rows = $this->query()
			->whereBetween('created_at',$created_at)
			->when($this->request->uid, function ($query) {
				$query->whereHas('conversation', function ($query) {
					$query->where('uid', $this->request->uid);
				});
			})
			->selectRaw('DATE(created_at) as date, COUNT(*) as count')
			->groupBy('date')
			->get()
			->pluck('count','date')
			->toArray();
		$series = [];
		foreach ($dates as $date) {
			$series[] = Arr::get($rows,$date,0);
		}

		$chartDatas = [
			'xAxis' => [
				'type' => 'category',
				'data' => $dates,
			],
			'yAxis' => [
				'type' => 'value',
			],
			'series' => [
				'name' => '提问次数',
				'data' => $series,
				'type' => 'line',
			],
			'tooltip' => [
				'trigger' => 'axis',
				'axisPointer' => [
					'type' => 'cross',
				],
			],
			'legend' => [
				'data' => 'dates.legend',
			],
		];
		return $chartDatas;
	}

}
